package com.squirrel.common.service.impl;

import com.squirrel.common.entity.UserComment;
import com.squirrel.common.exception.BaseException;
import com.squirrel.common.mapper.UserCommentMapper;
import com.squirrel.common.param.userComment.AddRelationshipParam;
import com.squirrel.common.param.userComment.RelationshipParam;
import com.squirrel.common.response.code.CodeEnum;
import com.squirrel.common.service.UserCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.lang.reflect.InvocationTargetException;

/**
 * <p>
 * UserCommentServiceImp 用户评论服务实现类
 * </p>
 *
 * @author 关远键
 * @since 2021/11/11 16:06
 */
@Service
public class UserCommentServiceImp extends ServiceImpl<UserCommentMapper, UserComment> implements UserCommentService {

    @Autowired
    private UserCommentMapper ucMapper;

    /**
     * 获取用户和评论之间的关系
     * @author 关远键
     * @date 2021/11/26 22:17
     * @param param 用户ID、评论ID
     * @return com.squirrel.common.entity.UserComment
     */
    @Override
    public UserComment getRelationship(RelationshipParam param) {
        UserComment relationShip = ucMapper.getRelationship(param.getUserId(), param.getCommentId());

        if (null == relationShip) {
            throw new BaseException(CodeEnum.NON_RESOURCE);
        }

        return relationShip;
    }

    /**
     * 添加用户与评论的关系
     * @author 关远键
     * @date 2021/11/26 22:18
     * @param param 相关参数
     * @return java.lang.Integer
     */
    @Override
    public Integer addRelationship(AddRelationshipParam param) {
        if (param.getIsGood() == 1 && param.getIsNotGood() == 1) {
            throw new BaseException(CodeEnum.PARAM_ERROR);
        }

        UserComment userComment = new UserComment();
        try {
            BeanUtils.copyProperties(userComment, param);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            throw new BaseException(CodeEnum.FAIL);
        }

        UserComment relationship = ucMapper.getRelationship(param.getUserId(), param.getCommentId());
        // 已存在关系，修改关系；否则插入关系
        if (null != relationship) {
            userComment.setUserCommentId(relationship.getUserCommentId());
            if (0 == ucMapper.updateById(userComment)) {
                throw new BaseException(CodeEnum.DB_EXCEPTION);
            }
        } else {
            if (0 == ucMapper.insert(userComment)){
                throw new BaseException(CodeEnum.DB_EXCEPTION);
            }
        }

        return userComment.getUserCommentId();
    }

}
